import React, { useState } from "react";
import FilterFooter from "../../../../components/FilterFooter";
import styles from "./index.module.css";

export default function FilterMore(props) {
  const [selectedValues, setselectedValues] = useState(props.defaultValues);

  const onTagClick = (value) => {
    let array = [...selectedValues];

    // 如果选中值中已经有当前值，说明用户此时再次点击该标签，那么就取消当前标签高亮效果
    if (selectedValues.includes(value)) {
      const index = array.indexOf(value);
      // 删除该标签
      array.splice(index, 1);
    } else {
      array.push(value);
    }
    setselectedValues(array);
  };

  // 清空选项
  const onCancel = () => {
    setselectedValues([]);
  };

  // 确认按钮事件
  const onOk = () => {
    const { type, onSave } = props;
    onSave(type, selectedValues);
  };

  // 渲染标签
  const renderFilters = (data) => {
    // 高亮类名： styles.tagActive
    return data.map((item) => {
      // 判断选中数组中是否有当前标签值
      const isSelected = selectedValues.includes(item.value);
      return (
        <div
          key={item.value}
          className={[styles.tag, isSelected ? styles.tagActive : ""].join(" ")}
          onClick={() => onTagClick(item.value)}
        >
          {item.label}
        </div>
      );
    });
  };

  const { characteristic, floor, oriented, roomType } = props.data;
  return (
    <div className={styles.root}>
      {/* 条件内容 */}
      <p>更多选项</p>
      <div className={styles.tags}>
        <div className={styles.name}>户型</div>
        <div className={styles.child}>{renderFilters(roomType)}</div>

        <div className={styles.name}>楼层</div>
        <div className={styles.child}>{renderFilters(floor)}</div>

        <div className={styles.name}>朝向</div>
        <div className={styles.child}>{renderFilters(oriented)}</div>

        <div className={styles.name}>特色</div>
        <div className={styles.child}>{renderFilters(characteristic)}</div>
      </div>
      <FilterFooter
        className={styles.buttons}
        cancelText="清除"
        onCancel={onCancel}
        onOk={onOk}
      />
    </div>
  );
}
